<template>
  <q-page class='flex flex-center fit'>
    <q-card bordered class='user-card column q-pa-lg q-gutter-md'>
      <div class='flex justify-center'>
        <q-avatar rounded size='100px'><img :src='avatar' /></q-avatar>
      </div>
      <div class='q-gutter-md'>
        <q-input outlined readonly label='用户名' :model-value='state.name' />
        <q-input outlined :readonly='!isEditing' label='联系方式' v-model='state.phone' />
        <q-input outlined :readonly='!isEditing' label='居住地址' v-model='state.address' />
      </div>
      <div class='flex justify-center' v-if='!isEditing'>
        <q-btn label='编 辑' color='primary' size='large' push
               @click='isEditing=!isEditing' v-if='!isEditing' />
      </div>
      <div class='flex justify-evenly' v-if='isEditing'>
        <q-btn label='取 消' text-color='primary' color='white' size='large' push
               @click='reset' />
        <q-btn label='完 成' color='primary' size='large' push
               @click='complete' />
      </div>
    </q-card>
  </q-page>
</template>

<script lang='ts'>
import { defineComponent, ref } from 'vue';
import _avatar from 'assets/avatar.jpg';
import { useStore } from 'src/status';
import { pinia } from 'boot/config';
import { changeUser } from 'src/services/api';
import { Notify } from 'quasar';
import { useRouter } from 'vue-router';

const avatar = _avatar as string;
const store = useStore(pinia);
export default defineComponent({
  name: 'User',
  setup() {
    const router = useRouter();
    const isEditing = ref(false);
    const state = ref({
      name: store.name,
      phone: store.phone,
      address: store.address
    });
    const reset = () => {
      state.value.phone = store.phone;
      state.value.address = store.address;
      isEditing.value = false;
    };
    const complete = async () => {
      try {
        console.log({
          telephone: state.value.phone,
          residence: state.value.address
        });
        const response = await changeUser({
          telephone: state.value.phone,
          residence: state.value.address
        });
        if (response.status === 0) {
          Notify.create({ message: '修改成功', type: 'positive', position: 'top' });
          setTimeout(() => router.go(0), 1000);
        }
      } catch (error) {
      }
    };
    return {
      avatar,
      state,
      isEditing,
      reset,
      complete
    };
  }
});
</script>
<style scoped>
.user-card {
  min-width: 50%;
  height: 100%
}

.q-btn {
  width: 100px;
}
</style>
